package com.api.server.service.impl;

import com.api.server.config.JwtTokenUtil;
import com.api.server.pojo.UserListPage;
import com.api.server.pojo.Puser;
import com.api.server.pojo.RespBean;
import com.api.server.pojo.User;
import com.api.server.mapper.UserMapper;
import com.api.server.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shi
 * @since 2022-04-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登陆之后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误，请重新输入！");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");

        }
        if (userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登陆成功",tokenMap);
    }

    @Override
    public User getAdminByUserName(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUseraccount,username).eq(User::getState,true));
    }

    @Override
    public int registeruser(Puser puser) {
        puser.setUserpassword(passwordEncoder.encode(puser.getUserpassword()));
        puser.setUsergrade("0");
        puser.setState("1");
        return userMapper.insert(puser);
    }

    @Override
    public int deleteaccount(Integer id) {
        return userMapper.deleteById(id);
    }

    @Override
    public User userById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public Map<String, Object> page(UserListPage userListPage) {
        Page pageInfo = new Page(userListPage.getPagenum(),userListPage.getPagesize());
        IPage<User> iPage = userMapper.selectPage(pageInfo,new QueryWrapper<User>().lambda().like(User::getUsergrade,userListPage.getQuery()));
        Map<String,Object> pageMap = new HashMap<>(3);
        //总条数
        pageMap.put("total",iPage.getTotal());
        //总页数
        pageMap.put("pages",iPage.getPages());
        //当前页码
        pageMap.put("pagenum",iPage.getSize());
        //数据集合
        pageMap.put("current_data",iPage.getRecords());

        return pageMap;
    }

    @Override
    public int updatebyId(User user) {
        if (user.getUserpassword()!=null){
            user.setUserpassword(passwordEncoder.encode(user.getUserpassword()));
            return userMapper.updateById(user);
        }
        return userMapper.updateById(user);
    }


}
